package com.company.cloud.company.client;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.redis.service.RedisUtils;
import com.company.cloud.company.modules.api.request.ThirdPlatformConfigGetRequest;
import com.company.cloud.company.modules.api.request.ThirdPlatformValidateContentRequest;
import com.company.cloud.company.modules.api.response.*;
import com.company.cloud.company.modules.api.service.CompanyConfigRemoteService;
import com.company.cloud.company.modules.cache.service.ThirdConfigCacheService;
import com.company.cloud.company.modules.mgr.service.BaseProfitMgrService;
import com.company.cloud.company.modules.mgr.service.CashConfigMgrService;
import com.company.cloud.company.modules.mgr.service.CustomerRewardMgrService;
import com.company.cloud.sdk.weixin.common.config.WxApiConfig;
import com.company.cloud.sdk.weixin.common.constant.WxErrorEnum;
import com.company.cloud.sdk.weixin.common.exception.WxException;
import com.company.cloud.sdk.weixin.mini.enums.WxMiniApiType;
import com.company.cloud.sdk.weixin.mini.model.Code2SessionResp;
import com.company.common.server.constant.LoginThirdChannelEnum;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Service
public class CompanyConfigRemoteServiceImpl implements CompanyConfigRemoteService {

    @Autowired
    private BaseProfitMgrService baseProfitMgrService;
    @Autowired
    private CashConfigMgrService cashConfigMgrService;
    @Autowired
    private CustomerRewardMgrService customerRewardMgrService;
    @Autowired
    private ThirdConfigCacheService thirdPlatformConfigCacheService;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public BaseClientResult<BaseProfitConfigResp> getBaseProfitConfig(String companyNo) {
        try {
            return BaseClientResult.success(baseProfitMgrService.get(companyNo));
        }catch (Exception e){
            return BaseClientResult.error(e);
        }
    }

    @Override
    public BaseClientResult<CashConfigResp> getCashConfig(String companyNo) {
        try {
            return BaseClientResult.success(cashConfigMgrService.get(companyNo));
        }catch (Exception e){
            return BaseClientResult.error(e);
        }
    }

    @Override
    public BaseClientResult<CustomerRewardResp> getCustomerReward(String companyNo) {
        try {
            return BaseClientResult.success(customerRewardMgrService.get(companyNo));
        }catch (Exception e){
            return BaseClientResult.error(e);
        }
    }

    @Override
    public BaseClientResult<ThirdPlatformConfigModel> getThirdPlatformConfig(ThirdPlatformConfigGetRequest params) {
        try {
            ValidatorUtils.validate(params);
            ThirdPlatformConfigModel data= thirdPlatformConfigCacheService.getThirdPlatformConfigByCache(
                    params.getCompanyNo(),params.getType());
            if(data==null){
                return BaseClientResult.error(BaseReturnEnum.DATA_NOT_EXISTS.getCode(),BaseReturnEnum.DATA_NOT_EXISTS.getMsg());
            }
            return BaseClientResult.success(data);
        }catch (Exception e){
            return BaseClientResult.error(e);
        }
    }


    @Override
    public BaseClientResult<String> getThirdPlatformAccessToken(ThirdPlatformConfigGetRequest params) {
        try {
            String access_token= this.getWXAccessToken();
            return BaseClientResult.success(access_token);
        }catch (Exception e){
            return BaseClientResult.error(e);
        }
    }

    @Override
    public BaseClientResult<ValidateContentResp> validateContent(ThirdPlatformValidateContentRequest params) {
        try {
            String access_token= this.getWXAccessToken();
            ValidateContentResp  data= this.getWxValidateContent(access_token,params.getContent());
            return BaseClientResult.success(data);
        }catch (Exception e){
            return BaseClientResult.error(e);
        }
    }


    private ValidateContentResp getWxValidateContent(String access_token,String content){
        String url=StrUtil.format("https://api.weixin.qq.com/wxa/msg_sec_check?access_token={}",access_token);
        Map<String,Object> params=new HashMap<>();
        params.put("content",content);
        String httpResp =HttpUtil.post(url,JSON.toJSONString(params));
        if (StrUtil.isEmpty(httpResp)) {
            throw new WxException(WxErrorEnum.WX_Http_ERROR);
        }

        JSONObject object = JSON.parseObject(httpResp);
        ValidateContentResp data=new ValidateContentResp();
        data.setCode(Convert.toInt(object.get("errcode")));
        data.setMsg(Convert.toStr(object.get("errmsg")));
        return data;
    }



    private String getWXAccessToken(){
        String cacheKey="wx:accesstoken:ptc";
        String access_token= redisUtils.get(cacheKey);
        if(StrUtil.isNotEmpty(access_token)){
            return access_token;
        }

        String companyNo="PTC";
        String type= LoginThirdChannelEnum.WxMini_User.getCode();

        ThirdPlatformConfigModel thirdConfig= thirdPlatformConfigCacheService.getThirdPlatformConfigByCache(companyNo,type);
        if(thirdConfig==null){
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        WxApiConfig config= BeanUtil.fillBeanWithMapIgnoreCase(thirdConfig.getThirdPlatformConfig(),new WxApiConfig(),false);

        String url= StrUtil.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}",config.getAppid(),config.getSecret());
        String httpResp =  HttpUtil.get(url);
        if (StrUtil.isEmpty(httpResp)) {
            throw new WxException(WxErrorEnum.WX_Http_ERROR);
        }
        JSONObject object = JSON.parseObject(httpResp);
        access_token= object.getString("access_token");
        if(StrUtil.isEmpty(access_token)){
            throw new WxException(WxErrorEnum.WX_Http_ERROR);
        }
        return access_token;
    }


}
